package com.redhat.auth.log.parse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 通过反射获取指定Object中指定属性的值，指定属性可以是级别子属性
 * 
 * @author lingen.liu
 * 
 */
public class ObjectValueReflection {

	/**
	 * 传递一个属性数组，返回最终值，可以是子属性
	 * 
	 * @param params
	 * @param objValue
	 * @return
	 */
	public static Object reflectObjectValueString(String key,Object objValue){
		Object obj =  objValue;
		String[] params=null;
		if(key.contains("."))params = key.split("\\.");
		else params = new String[]{key};
		if(objValue instanceof Collection){
			List objList = new ArrayList();
			Collection objCollection = (Collection)(objValue);
			for(Object val:objCollection){
				obj = val;
				for(String param:params){
					if(param.trim()==null || "".equals(param.trim()))continue;
					obj = getReflectionValue(param.trim(),obj);
				}
				objList.add(obj);
			}
			if(objList.size()==1)return objList.get(0);
			return objList;
		}
		//当前对象是个数组
        if(objValue instanceof Object[]){
        	List objList = new ArrayList();
        	Object[] objCollection = (Object[])(objValue);
        	for(Object val:objCollection){
        		if(val==null)continue;
				obj = val;
				for(String param:params){
					if(param.trim()==null || "".equals(param.trim()))continue;
					obj = getReflectionValue(param.trim(),obj);
				}
				objList.add(obj);
			}
        	if(objList.size()==1)return objList.get(0);
			return objList;
		}
		for(String param:params){
			if(param.trim()==null || "".equals(param.trim()))continue;
			obj = getReflectionValue(param.trim(),obj);
		}
		return obj;
	}

	/**
	 * 传递一个属性数组，返回最终值，可以是子属性
	 * 
	 * @param params
	 * @param objValue
	 * @return
	 */
	public static Object reflectObjectValueList(List<String> params,
			Object objValue) {
		Object obj = objValue;
		for (String param : params) {
			if (param.trim() == null || "".equals(param.trim()))
				continue;
			obj = getReflectionValue(param.trim(), obj);
		}
		return obj;
	}

	public static Object getReflectionValue(String param, Object value) {
		Object obj = null;
		if(param.equals(""))return value;
		try {
			Class c = value.getClass();
			String methodName = "get" + param.substring(0, 1).toUpperCase()
					+ param.substring(1);
			Method method = c.getMethod(methodName, null);
			obj = method.invoke(value, null);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
